using UnityEngine;
using System.Collections;

/// \class  gkAbyssalGiantPlantTipInteraction
/// \brief  Plant tip interaction
[AddComponentMenu("GK/AbyssalGiant/Plant/gkAbyssalGiantPlantTipInteraction")]
[RequireComponent(typeof(gkPhysicComponent))]
[RequireComponent(typeof(gkTransformPhysicController))]
public class gkAbyssalGiantPlantTipInteraction : MonoBehaviour 
{
	/// The interation max force
	public float MaxInteractionForce = 5.0f;
	
	/// The interaction direction scale
	public Vector3 InteractionDirectionScale = new Vector3(1.0f, 0.25f, 0.0f);
	
	/// The interation max force
	public float InteractionRadialExponent = 0.5f;
	
	/// The Physic component
	private gkPhysicComponent m_rPhysicComponent;
	
	/// The Physic component
	private gkPhysicController m_rRootPhysicController;
	
	/// The sphere collider
	private SphereCollider m_rSphereCollider;
	
	/// \brief  Called just after the game begin to play
    void Start()
    {
        // Get the physic component
        m_rPhysicComponent = GetComponent<gkPhysicComponent>();
		
		// Get the root physic controller
		m_rRootPhysicController = transform.root.GetComponent<gkPhysicController>();
		
		// Grab the collider
		m_rSphereCollider = collider as SphereCollider;
	}
	
	/// \brief  Call at the overlapping beginning
	void OnTriggerStay(Collider a_rCollisionInfo)
	{
		float fOwnerToColliderDistance;
		Vector3 f3OwnerToCollider;
		Vector3 f3ColliderVelocity;
		float fInteractionPercentage;
		Vector3 f3InteractionForce;
		gkPhysicController rColliderPhysicController;
		
		if(a_rCollisionInfo.gameObject.name == "Submarine")
		{
		
			// Compute the distance vector between the owner and the collider
			f3OwnerToCollider = a_rCollisionInfo.gameObject.transform.position - transform.position;
			fOwnerToColliderDistance = f3OwnerToCollider.magnitude;
			
			// Get the collider velocity
			rColliderPhysicController = a_rCollisionInfo.gameObject.GetComponent<gkPhysicController>();
			f3ColliderVelocity = rColliderPhysicController.GetLinearVelocity()
				- m_rRootPhysicController.GetLinearVelocity();
			
			// Compute the interaction force
			fInteractionPercentage = (fOwnerToColliderDistance/(m_rSphereCollider.radius * transform.lossyScale.y));
			fInteractionPercentage = 1.0f - Mathf.Pow(fInteractionPercentage, InteractionRadialExponent);
			f3InteractionForce = MaxInteractionForce * f3ColliderVelocity; 
			
			// Scale the interaction
			f3InteractionForce.x *= InteractionDirectionScale.x;
			f3InteractionForce.y *= InteractionDirectionScale.y;
			f3InteractionForce.z *= InteractionDirectionScale.z;
			
			m_rPhysicComponent.AddForce(f3InteractionForce);
		}
	}
}